﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace VolunteerHubAdapter.Views
{
    /// <summary>
    /// Interaction logic for SettingsView.xaml
    /// </summary>
    public partial class SettingsView : Window
    {
        public SettingsView()
        {
            InitializeComponent();
            this.DataContextChanged += SettingsWindow_DataContextChanged;
            this.Closed += SettingsWindow_Closed;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == CancelButton)
                this.DialogResult = false;
            else
                this.DialogResult = true;

            this.Close();
        }

        private ViewModels.SettingsViewModel _viewModel;

        void SettingsWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (Object.Equals(_viewModel, this.DataContext))
                return;

            if (_viewModel != null)
            {
                _viewModel.RequestClose -= _viewModel_RequestClose;
                _viewModel.TestConnectionResult -= this.TestConnection;
                _viewModel.ShowHelp -= _viewModel_ShowHelp;
            }
            _viewModel = (ViewModels.SettingsViewModel)this.DataContext;
            _viewModel.RequestClose += _viewModel_RequestClose;
            _viewModel.TestConnectionResult += this.TestConnection;
            _viewModel.ShowHelp += _viewModel_ShowHelp;
            this.Title = "VolunteerHub Connection Information (ver " + _viewModel.Adapter.Version.ToString() + ")";
        }

        private void _viewModel_ShowHelp(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://omatic-importomatic.helpdocsonline.com/volunteerhub");
        }

        void SettingsWindow_Closed(object sender, EventArgs e)
        {
            if (_viewModel != null)
                _viewModel.RequestClose -= _viewModel_RequestClose;
        }

        void _viewModel_RequestClose()
        {
            this.Close();
        }

        void TestConnection(object sender, VolunteerHubEventArgs e)
        {
            if (e.Successful == true)
                System.Windows.MessageBox.Show("The connection test succeeded.");
            else
                System.Windows.MessageBox.Show("The connection test failed: " + Environment.NewLine + e.ErrorMessage);
        }

        private void Border_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            this.DragMove();
        }
    }
}
